#include "urllib.h"

namespace libzq
{
	string urlencode(const string& s)
	{
		static const char lookup[] = "0123456789abcdef";
		std::stringstream e;
		for (int i = 0, ix = s.length(); i < ix; i++)
		{
			const char& c = s[i];
			if ((48 <= c && c <= 57) ||//0-9
				(65 <= c && c <= 90) ||//abc...xyz
				(97 <= c && c <= 122) || //ABC...XYZ
				(c == '-' || c == '_' || c == '.' || c == '~')
				)
			{
				e << c;
			}
			else
			{
				e << '%';
				e << lookup[(c & 0xF0) >> 4];
				e << lookup[(c & 0x0F)];
			}
		}
		return std::move(e.str());
	}

	string urldecode(const string& s)
	{
		std::stringstream e;
		for (int i = 0, ix = s.length(); i < ix;)
		{
			if (s[i] == '%')
			{
				char c = (char2int(s[i + 1]) << 4) | char2int(s[i + 2]);
				e << c;
				i = i + 3;
			}
			else if (s[i] == '+')
			{
				e << ' ';
				i++;
			}
			else
			{
				e << s[i];
				i++;
			}
		}
		return std::move(e.str());
	}

	char char2int(char ch)
	{
		if (ch >= '0' && ch <= '9')
		{
			return (char)(ch - '0');
		}
		if (ch >= 'a' && ch <= 'f')
		{
			return (char)(ch - 'a' + 10);
		}
		if (ch >= 'A' && ch <= 'F')
		{
			return (char)(ch - 'A' + 10);
		}
		return -1;
	}

}